﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Microsoft.SharePoint;
using System.Configuration;
using Microsoft.SharePoint.Administration;
using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;
using System.Data;
using TemplateLibraryConnector.Utility;

namespace TemplateLibraryConnector.Data
{
    public class LastUsedTemplates : BaseTemplates
    {
        private const string LastUsedProperty = "LastUsedTemplates";
        private const string LastUsedDisplayName = "Last Used Templates";
        public LastUsedTemplates(TemplateLibraryConnectorSettings settings)
            : base(settings)
        {
        }
        public override DataTable Items()
        {
            return GetLastUsedItems(Settings.GetTemplateHubAddress(string.Empty));
        }
        protected DataTable GetLastUsedItems(string templateUrl)
        {
            var currentUser = SPContext.Current.Web.CurrentUser.LoginName;
            var items = new List<SPListItem>();
            var dt = new DataTable();
            using (var siteCollection = new SPSite(templateUrl))
            {
                using (var webSite = siteCollection.OpenWeb())
                {
                    var serverContext = SPServiceContext.GetContext(siteCollection);
                    var upcm = new UserProfileConfigManager(serverContext);
                    var userProfileManager = new UserProfileManager(serverContext);
                    var ppm = upcm.ProfilePropertyManager;
                    if (userProfileManager.UserExists(currentUser))
                    {
                        // Retreive the user profile.
                        var userProfile = userProfileManager.GetUserProfile(currentUser);
                        if (ppm.GetCoreProperties().GetPropertyByName(LastUsedProperty) != null)
                        {
                            var lastUsedProp = userProfile[LastUsedProperty];
                            var doclibAbsoluteUrl = Settings.GetTemplateHubAddress(string.Empty);
                            var listId = new Guid(Settings.TemplateListIds);
                            using (var site = new SPSite(doclibAbsoluteUrl))
                            {
                                var relativeSubWebUrl = doclibAbsoluteUrl.Replace(site.Url, "");
                                using (var web = site.OpenWeb(relativeSubWebUrl))
                                {
                                    var rootFolder = web.Lists[listId].RootFolder;

                                    var index = 0;
                                    var userProfileNeedsUpdate = false;
                                    foreach (var fileProp in lastUsedProp)
                                    {
                                        try
                                        {
                                            var file = rootFolder.Files[fileProp.ToString()];
                                            items.Add(file.Item);
                                        }
                                        catch (Exception)
                                        {
                                            // File does not exist anymore in hub library. Remove from user profile prop
                                            userProfile[LastUsedProperty].RemoveAt(index);
                                            userProfileNeedsUpdate = true;
                                        }
                                        index++;
                                    }
                                    if (userProfileNeedsUpdate)
                                        userProfile.Commit();

                                    //items.AddRange(from object prop in property select rootFolder.Files[prop.ToString()].Item);
                                    items.Reverse();
                                    dt = TemplateLibraryUtility.ToDataTable(items);
                                }
                            }
                        }
                    }
                }
            }
            return dt;
        }
        public static void UpdateLastUsedProperty(string lastUsedUrl, string currentUser, Guid siteCollection)
        {
            lastUsedUrl = HttpUtility.UrlDecode(lastUsedUrl);
            var currUser = currentUser;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (var site = new SPSite(siteCollection))
                {

                    if (HttpContext.Current.Request.HttpMethod == "GET")
                    {
                        HttpContext.Current = null;
                    }
                    var serverContext = SPServiceContext.GetContext(site);
                    var upcm = new UserProfileConfigManager(serverContext);
                    var userProfileManager = new UserProfileManager(serverContext);
                    var ppm = upcm.ProfilePropertyManager;

                    try
                    {
                        // Retreive the user profile.
                        var userProfile = userProfileManager.GetUserProfile(currUser);
                        // Check whether the property exists.
                        if (ppm.GetCoreProperties().GetPropertyByName(LastUsedProperty) == null)
                        {
                            var cpm = ppm.GetCoreProperties();
                            var coreProperty = cpm.Create(false);
                            coreProperty.Name = LastUsedProperty;
                            coreProperty.DisplayName = LastUsedDisplayName;
                            coreProperty.Type = PropertyDataType.StringMultiValue;
                            coreProperty.Separator = MultiValueSeparator.Comma;
                            coreProperty.Length = 3600;
                            coreProperty.IsMultivalued = true;
                            coreProperty.IsSearchable = false;
                            cpm.Add(coreProperty);
                            var ptPropertyManager = ppm.GetProfileTypeProperties(ProfileType.User);
                            var ptProperty = ptPropertyManager.Create(coreProperty);
                            ptProperty.IsVisibleOnEditor = false;
                            ptProperty.IsVisibleOnViewer = false;
                            ptPropertyManager.Add(ptProperty);
                            var psm = ProfileSubtypeManager.Get(serverContext);
                            var psType = psm.GetProfileSubtype(ProfileSubtypeManager.GetDefaultProfileName(ProfileType.User));
                            var pfPropertyManager = psType.Properties;
                            var pstProperty = pfPropertyManager.Create(ptProperty);
                            pstProperty.IsUserEditable = true;
                            pstProperty.PrivacyPolicy = PrivacyPolicy.OptIn;
                            pstProperty.DefaultPrivacy = Privacy.Private;
                            pfPropertyManager.Add(pstProperty);

                        }
                        if (userProfile[LastUsedProperty].Count > 10)
                            userProfile[LastUsedProperty].RemoveAt(0);

                        for (var i = 0; i < userProfile[LastUsedProperty].Count; i++)
                        {
                            if (userProfile[LastUsedProperty][i] as string == lastUsedUrl)
                                userProfile[LastUsedProperty].RemoveAt(i);
                        }
                        userProfile[LastUsedProperty].Add(lastUsedUrl);
                        userProfile.Commit();
                    }
                    catch (DuplicateEntryException ex1)
                    {
                    }
                    catch (Exception ex2)
                    {
                    }
                }
            });
        }
    }
}
